package order

import (
	"context"
	"group-buy/group_buy/internal/models"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type WriteOffListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWriteOffListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WriteOffListLogic {
	return &WriteOffListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WriteOffListLogic) WriteOffList(req *types.WriteOffListReq) (resp *types.WriteOffListRsp, err error) {
	data := make([]*models.WriteOffRecord, 0)
	sql := l.svcCtx.Engine.Where("")
	if req.UserId > 0 {
		sql = sql.And("write_off_user_id =?", req.UserId)
	}
	if req.BusinessId > 0 {
		sql = sql.And("business_id=?", req.BusinessId)
	}
	if req.ProductId > 0 {
		sql = sql.And("product_id=?", req.ProductId)
	}
	if req.OrderId > 0 {
		sql = sql.And("order_id=?", req.OrderId)
	}
	if req.MemberId > 0 {
		sql = sql.And("user_id=?", req.MemberId)
	}
	count, err := sql.Desc("id").Limit(req.Size, (req.Page-1)*req.Size).FindAndCount(&data)
	if err != nil {
		return nil, err
	}
	list := make([]*types.WriteOff, len(data), len(data))
	for i, _ := range data {

		list[i] = &types.WriteOff{
			Id:               data[i].Id,
			OrderId:          data[i].OrderId,
			UserId:           data[i].UserId,
			ProductId:        data[i].ProductId,
			BusinessId:       data[i].BusinessId,
			ProductName:      data[i].ProductName,
			ProductCover:     data[i].ProductCover,
			BusinessName:     data[i].BusinessName,
			UserName:         data[i].UserName,
			WriteOffUserId:   data[i].WriteOffUserId,
			WriteOffUserName: data[i].WriteOffUserName,
			WriteOffTime:     data[i].WriteOffTime,
		}
	}

	return &types.WriteOffListRsp{
		List:  list,
		Count: count,
	}, nil
}
